package org.jeecg.modules.dataSet.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.dataSet.entity.DataSet;
import org.jeecg.modules.dataSet.service.IDataSetService;
import org.jeecg.modules.userFormula.entity.UserFormula;
import org.jeecg.modules.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 数据集
 * @Author: jeecg-boot
 * @Date: 2023-05-31
 * @Version: V1.0
 */
@Api(tags = "数据集")
@RestController
@RequestMapping("/dataSet/dataSet")
@Slf4j
public class DataSetController extends JeecgController<DataSet, IDataSetService> {
    @Autowired
    private IDataSetService dataSetService;
    @Value("${zf-jqxx-service.url}")
    private String zfserviceUrl;

    /**
     * 分页列表查询
     *
     * @param dataSet
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "数据集-分页列表查询")
    @ApiOperation(value = "数据集-分页列表查询", notes = "数据集-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<DataSet>> queryPageList(DataSet dataSet,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        QueryWrapper<DataSet> queryWrapper = QueryGenerator.initQueryWrapper(dataSet, req.getParameterMap());
        Page<DataSet> page = new Page<DataSet>(pageNo, pageSize);
        IPage<DataSet> pageList = dataSetService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param dataSet
     * @return
     */
    @AutoLog(value = "数据集-添加")
    @ApiOperation(value = "数据集-添加", notes = "数据集-添加")
    //@RequiresPermissions("dataSet:tb_data_set:add")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> add(@RequestBody DataSet dataSet) {
        Date d = new Date();
        dataSet.setCode("dt_" + DateUtils.yyyymmddhhmmss.get().format(d));
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("dataset_name", dataSet.getCode());
        paramsMap.put("slot_no", dataSet.getSlotNo());
        paramsMap.put("begin_date", dataSet.getBeginDate());
        paramsMap.put("end_date", dataSet.getEndDate());
        try {
            //ds/gen_ds?dataset_name=dt_2023071602&slot_no=2231&begin_date=2023-05-01&end_date=2023-05-30&ds_type=%E5%AE%9E%E6%97%B6%E6%95%B0%E6%8D%AE%E9%9B%86
            String url = zfserviceUrl + "/ds/gen_ds";
            url += "?dataset_name=" + dataSet.getCode();
            url += "&slot_no=" + dataSet.getSlotNo();
            url += "&begin_date=" + dataSet.getBeginDate();
            url += "&end_date=" + dataSet.getEndDate();
            url += "&ds_type=" + URLEncoder.encode(dataSet.getDsType(), "utf-8");
            JSONObject object = HttpClientUtil.sendPost(url, paramsMap);
            if (object == null) {
                return Result.error("保存失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                JSONObject data = JSON.parseObject(object.get("data").toString());
                dataSet.setFields(Integer.parseInt(data.get("fields").toString()));
                dataSet.setDataSize(Integer.parseInt(data.get("length").toString()));
                dataSetService.save(dataSet);
                return Result.OK("操作成功");
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("保存失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("保存失败，请联系管理员");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "数据集-通过id删除")
    @ApiOperation(value = "数据集-通过id删除", notes = "数据集-通过id删除")
    //@RequiresPermissions("dataSet:tb_data_set:delete")
    @DeleteMapping(value = "/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        DataSet dataSetInfo = dataSetService.getById(id);
        try {
            String url = zfserviceUrl + "/feature/del_dataset?dataset_name=" + dataSetInfo.getCode();
            JSONObject object = HttpClientUtil.sendPost(url, new HashMap<>());
            if (object == null) {
                return Result.error("删除失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                dataSetService.removeById(id);
                return Result.OK("删除成功");
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("删除失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("删除失败，请联系管理员");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "数据集-批量删除")
    @ApiOperation(value = "数据集-批量删除", notes = "数据集-批量删除")
    //@RequiresPermissions("dataSet:tb_data_set:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.dataSetService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "数据集-通过id查询")
    @ApiOperation(value = "数据集-通过id查询", notes = "数据集-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<DataSet> queryById(@RequestParam(name = "id", required = true) String id) {
        DataSet dataSet = dataSetService.getById(id);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dataSet);
    }

    @ApiOperation(value = "数据集-通过code查询", notes = "数据集-通过code查询")
    @GetMapping(value = "/queryByCode")
    public Result<DataSet> queryByCode(@RequestParam(name = "code", required = true) String code) {
        LambdaQueryWrapper<DataSet> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataSet::getCode, code);
        DataSet dataSet = dataSetService.getOne(queryWrapper);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(dataSet);
    }
    /**
     * 导出excel
     *
     * @param request
     * @param dataSet
     */
    //@RequiresPermissions("dataSet:tb_data_set:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, DataSet dataSet) {
        return super.exportXls(request, dataSet, DataSet.class, "数据集");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("dataSet:tb_data_set:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, DataSet.class);
    }

    @ApiOperation(value = "数据集-通过id查询明细", notes = "数据集-通过id查询明细")
    @GetMapping(value = "/queryByIdDetail")
    public Result<IPage<DataSet>> queryByIdDetail(@RequestParam(name = "id", required = true) String id,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        DataSet dataSet = dataSetService.getById(id);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        try {
            String url = zfserviceUrl + "/ds/browse_ds?ds_name=" + dataSet.getCode();
            url +="&page_size="+pageSize;
            url+= "&page_number="+pageNo;
            JSONObject object = HttpClientUtil.sendGet(url, new HashMap<>());
            if (object == null) {
                return Result.error("获取数据失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                IPage<DataSet> rult =  new Page<>(pageNo, pageSize);;
                rult.setRecords((List<DataSet>)object.get("data"));
                rult.setCurrent(pageNo);
                rult.setTotal(Long.parseLong(object.get("length").toString()));
                return Result.ok(rult);
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("获取数据失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("获取数据失败，请联系管理员");
        }
    }

    @ApiOperation(value = "数据集-通过id查询数据概要", notes = "数据集-通过id查询数据概要")
    @GetMapping(value = "/queryByIdDesc")
    public Result<Object> queryByIdDesc(@RequestParam(name = "id", required = true) String id) {
        DataSet dataSet = dataSetService.getById(id);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        try {
            String url = zfserviceUrl + "/ds/ds_desc?ds_name=" + dataSet.getCode();
            JSONObject object = HttpClientUtil.sendGet(url, new HashMap<>());
            if (object == null) {
                return Result.error("获取数据失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK(object.get("data"));
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("获取数据失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("获取数据失败，请联系管理员");
        }
    }


    @ApiOperation(value = "数据集-通过id查询质量分析", notes = "数据集-通过id查询质量分析")
    @GetMapping(value = "/queryByIdQuality")
    public Result<Object> queryByIdQuality(@RequestParam(name = "id", required = true) String id) {
        DataSet dataSet = dataSetService.getById(id);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        try {
            String url = zfserviceUrl + "/ds/ds_quality?ds_name=" + dataSet.getCode();
            JSONObject object = HttpClientUtil.sendGet(url, new HashMap<>());
            if (object == null) {
                return Result.error("获取数据失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK(object.get("data"));
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("获取数据失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("获取数据失败，请联系管理员");
        }
    }

    @AutoLog(value = "数据集-数据清洗")
    @ApiOperation(value = "数据集-数据清洗", notes = "数据集-数据清洗")
    @PostMapping(value = "/fillNa")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> fillNa(@RequestParam(name = "dataSetId", required = true) String dataSetId
            ,@RequestParam(name = "fieldName", required = true) String fieldName
            ,@RequestParam(name = "fieldValue", required = true) String fieldValue) {
        DataSet dataSet = dataSetService.getById(dataSetId);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        try {
            String url = zfserviceUrl + "/ds/ds_fill_na";
            url += "?ds_name=" + dataSet.getCode();
            url += "&field_name=" + fieldName;
            url += "&value=" + fieldValue;
            JSONObject object = HttpClientUtil.sendPost(url, null);
            if (object == null) {
                return Result.error("保存失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK("操作成功");
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("保存失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("保存失败，请联系管理员");
        }
    }

    @AutoLog(value = "数据集-数据清洗")
    @ApiOperation(value = "数据集-数据清洗", notes = "数据集-数据清洗")
    @PostMapping(value = "/dsUpdate")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> dsUpdate(@RequestParam(name = "dataSetId", required = true) String dataSetId,
                                   @RequestParam(name = "fieldName", required = true) String fieldName,
                                   @RequestParam(name = "fieldValue", required = true) String fieldValue,
                                   @RequestParam(name = "condition", required = true) String condition) {
        DataSet dataSet = dataSetService.getById(dataSetId);
        if (dataSet == null) {
            return Result.error("未找到对应数据");
        }
        try {
            String url = zfserviceUrl + "/ds/ds_update";
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("ds_name", dataSet.getCode());
            paramsMap.put("field_name", fieldName);
            paramsMap.put("value", fieldValue);
            paramsMap.put("condition", condition);
            url+="?ds_name="+ paramsMap.get("ds_name")+"&field_name="+paramsMap.get("field_name")+
                    "&value="+paramsMap.get("value")+"&condition="+paramsMap.get("condition");
            JSONObject object = HttpClientUtil.sendPost(url, paramsMap);
            if (object == null) {
                return Result.error("保存失败");
            }
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                return Result.OK("操作成功");
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("保存失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("保存失败，请联系管理员");
        }
    }
}
